package com.gable.common.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;
import java.util.Map;

/**
 * Created by Lesson on 2017/7/26.
 */
public class HttpPost {

    public static ReturnResultUtil HttpPostClient(String url, Map<String, String> headMap, Map<String, String> bodyMap) {
        try {
            HttpClient client = new HttpClient();
            PostMethod method = new PostMethod(url);
            method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
            if (headMap != null && headMap.size() > 0) {
                for (Map.Entry<String, String> entry : headMap.entrySet()) {
                    method.setRequestHeader(entry.getKey(), entry.getValue());
                }
            }

            if (bodyMap != null && bodyMap.size() > 0) {
                for (Map.Entry<String, String> entry : bodyMap.entrySet()) {
                    method.addParameter(entry.getKey(), entry.getValue());
                }
            }
            HttpMethodParams param = method.getParams();
            param.setContentCharset("UTF-8");
            int resultCode = client.executeMethod(method);
            if (resultCode != 200) {
                return new ReturnResultUtil(500, "发送失败", null);
            }
            String result = readStream(method.getResponseBodyAsStream(), "UTF-8");
            ReturnResultUtil rm = JSON.parseObject(result,ReturnResultUtil.class);
            return rm;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500, "发送出现异常",null);
    }


    public static String readStream(InputStream in, String charset) throws IOException {
        StringBuilder buf = new StringBuilder();
        int ch = -1;
        Reader reader = new InputStreamReader(new BufferedInputStream(in), charset);
        while (-1 != (ch = reader.read())) {
            buf.append((char) ch);
        }
        return buf.toString();
    }


}
